package ic.doc.co2nudge.client.utils;

import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;

import ic.doc.co2nudge.shared.model.User;

import ic.doc.co2nudge.client.utils.DataServiceFactory;
import ic.doc.co2nudge.client.utils.events.UserServiceEvent;
import ic.doc.co2nudge.client.utils.events.UserServiceEventListener;

public class UserService {

	private static User currentUser;
	
	private static UserService 					userService;
	private static UserServiceEventListener 	userServiceEventListener;
	
	public static UserService getUserService(){
		if (userService==null)
			userService=new UserService();
		
		return userService;
	}
	
	public static void removeUserServiceEventListener(){
		userServiceEventListener=null;
	}
	
	public static void addUserServiceEventListener(UserServiceEventListener listener){
		userServiceEventListener=listener;
	}

	protected void fireUserServiceEvent(UserServiceEvent e){
		userServiceEventListener.done(e);
	}
	
	public void authenticate(String username, String password) {
		userService.getUser(username, password);
	}
	
	public User getCurrentUser(){
		return currentUser;
	}
	
	public void saveUser(User user){
		return;
	}
	
	public void getUser(String username, String password){
		DataServiceFactory.getDataService().getUser(username, password, 
				new AsyncCallback<User>(){
			
					UserServiceEvent e=
						new UserServiceEvent(false);					

					@Override
					public void onFailure(Throwable caught) {
						fireUserServiceEvent(e);
					}

					@Override
					public void onSuccess(User user) {
						
						if (user!=null){
							e=new UserServiceEvent(true);
							currentUser=user;
						}
						
						fireUserServiceEvent(e);
					}
		});
	}
	
	public List<User> getAllUsers(){
		return null;
	}
}
